'''
Created on Mar 7, 2016

@author: JimmyMo
'''
import elasticsearch
from elasticsearch import helpers
from writter.perfsynwritter import Writter

class Writter4ES(Writter):
    def __init__(self):
        super().__init__()
        self.es = elasticsearch.Elasticsearch(self.hosts)
        
    def _parse_options(self):
#         Writter._parse_options(self)
        self.index_name = "size-test-2"
        self.type_name = "table1"
        self.hosts = ["127.0.0.1:9200"]
        self.batch_size = 100000
    def flush_db(self):
        try:
            self.es.indices.delete(self.index_name)
        except:
            pass
        self.es.indices.create(self.index_name) 
    def _write(self):
#         logs4all_devices = self.log4all_devices
        logs4all_devices = self.event_buffer_list
        print('inserting elasticsearch...')
        index_name = self.index_name
        type_name = self.type_name
        es = self.es
#         es = elasticsearch.Elasticsearch(self.hosts)
#         try:
#             es.indices.delete(index_name)
#         except:
#             pass
    #     es.indices.create(index_name) 
        es.cluster.health(wait_for_status="yellow") 
    #     res = es.indices.put_mapping(index=index_name, 
    #                              doc_type=type_name, 
    #                              body={type_name: {"properties": mapping}}) 
        size = self.batch_size
        n = 0
        actions = []
        for i, doc in enumerate(logs4all_devices):
#             print("processing %d..." % i)
#             for doc in g4device:
            action = {
                      "_index": index_name,
                      "_type": type_name,
                      "_source": doc
                      }
            actions.append(action)
                
            n += 1 
            if n >= size:             
                n = 0 
                helpers.bulk(es, actions) 
                actions = [] 
        
        if actions: 
            helpers.bulk(es, actions)     
        
        print('done inserting...')